<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">
          <el-form-item label="项目名称">
            <el-input v-model="listQuery.proName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>
          <el-form-item label="责任人">
            <el-input v-model="listQuery.proPersonLiable"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>
          <el-form-item label="所属部门">
            <el-select v-model="listQuery.proDepartment"
                       placeholder="请选择部门">
              <el-option v-for="item in departmentList"
                         :key="item.departmentName"
                         :label="item.departmentName"
                         :value="item.departmentName">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="right-box">
          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini"
                     @click="reset" type="info">重置
          </el-button>
          <el-button size="mini"
                     type="success" @click="handleCreate">新增
          </el-button>
        </div>
      </template>
    </search-box>

    <el-tabs v-model="activeName" @tab-click="handleClick">

      <el-tab-pane label="我的项目" name="myProject">
      <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>

        <el-table-column prop="proCode"
                         label="项目编码">
        </el-table-column>

        <el-table-column prop="proName"
                         label="项目名称">
        </el-table-column>
        <el-table-column prop="proPersonInitiator"
                         label="项目发起人">
        </el-table-column>
        <el-table-column prop="proPersonLiable"
                         label="项目责任人">
        </el-table-column>
        <el-table-column prop="proDepartment"
                         label="项目责任部门">
        </el-table-column>
        <el-table-column prop="proStartTime"
                         label="项目起始时间">

          <template slot-scope="scope">
            {{scope.row.proStartTime.substring(0,10)}}
          </template>

        </el-table-column>
        <el-table-column prop="proEndTime"
                         label="项目终止时间">

          <template slot-scope="scope">
            {{scope.row.proEndTime.substring(0,10)}}
          </template>
        </el-table-column>

        <el-table-column prop="createDate"
                         label="项目创建时间">
          <template slot-scope="scope">
            {{scope.row.createDate.substring(0,10)}}
          </template>

        </el-table-column>

        <el-table-column prop="proSchedule"
                         label="项目进度">
          <template slot-scope="scope">
            {{scope.row.proSchedule}} %
          </template>

        </el-table-column>

        <el-table-column prop="proParentCode"
                         label="所属项目">
          <template slot-scope="scope">
            <span v-if="scope.row.proParentCode!=null&&scope.row.proParentCode!=''&&scope.row.proParentCode!='0'" style="color: #1e88f7">{{scope.row.proParentName}}</span>
            <span v-else style="color:green">初始项目</span>
          </template>

        </el-table-column>

        <el-table-column prop="customerName"
                         label="客户名称">
        </el-table-column>

        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" >
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>
    </div>
      </el-tab-pane>

      <el-tab-pane label="当前项目" name="currentProject">当前项目</el-tab-pane>

      <el-tab-pane label="历史项目" name="pastProject">历史项目</el-tab-pane>

    </el-tabs>



    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      style="margin-top: -5%"
    >
      <el-form ref="form" :rules="rules" :model="listQuery" label-width="120px">

        <el-form-item label="项目编码" prop="proCode">
          <el-input v-model="listQuery.proCode" ></el-input>
        </el-form-item>
        <el-form-item label="项目名称" prop="proName">
          <el-input v-model="listQuery.proName" ></el-input>
        </el-form-item>

        <el-form-item label="父项目名称" >

          <el-select v-model="listQuery.proParentCode"
                     placeholder="不选当前项目即为父项目">
            <el-option v-for="item in listParent"
                       :key="item.proCode"
                       :label="item.proName"
                       :value="item.proCode">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="项目发起人部门" >
          <el-select v-model="listQuery.departmentName" @change="getUsersList"
                     placeholder="请选择项目发起人部门">
            <el-option v-for="item in departmentList"
                       :key="item.departmentName"
                       :label="item.departmentName"
                       :value="item.departmentName">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="项目发起人" prop="proPersonInitiator">
          <el-select v-model="listQuery.proPersonInitiator"
                     placeholder="请选择项目发起人" >
            <el-option v-for="item in usersList"
                       :key="item.userName"
                       :label="item.userName"
                       :value="item.userName">
            </el-option>
          </el-select>


        </el-form-item>
        <el-form-item label="项目责任人部门" >


          <el-select v-model="listQuery.departmentName1" @change="getUsersList"
                     placeholder="请选择项目责任人部门">
            <el-option v-for="item in departmentList"
                       :key="item.departmentName"
                       :label="item.departmentName"
                       :value="item.departmentName">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="项目责任人" prop="proPersonLiable">
          <el-select v-model="listQuery.proPersonLiable"
                     placeholder="请选择项目责任人" >
            <el-option v-for="item in usersList"
                       :key="item.userName"
                       :label="item.userName"
                       :value="item.userName">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="项目起始时间" prop="proStartTime">
          <el-date-picker type="date" placeholder="选择日期" v-model="listQuery.proStartTime" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="项目结束时间" prop="proEndTime">
          <el-date-picker type="date" placeholder="选择日期" v-model="listQuery.proEndTime" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="项目所属部门" prop="proDepartment">
          <el-select v-model="listQuery.proDepartment"
                     placeholder="请选择部门">
            <el-option v-for="item in departmentList"
                       :key="item.departmentName"
                       :label="item.departmentName"
                       :value="item.departmentName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="项目客户名称" >
          <el-select v-model="listQuery.customerName"
                     placeholder="请选择项目客户名称">
            <el-option v-for="item in customerlist"
                       :key="item.customerName"
                       :label="item.customerName"
                       :value="item.customerName">
            </el-option>
          </el-select>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary" @click="onSubmit" >确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import * as apiUser from '@/api/user'
  import * as customerManage from '@/api/customer/customerManage';
  import * as myProject from '@/api/projectOa/myProject'
  import * as department from '@/api/system-setting/department'
  import * as position from '@/api/system-setting/position'
  import * as user from '@/api/system-setting/user'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import { MessageBox } from 'element-ui'
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'

  export default {
    name: 'department',
    components: { Pagination, searchBox },
    directives: { waves },
    filters: {},
    data() {
      return {
        list: null,
        total: 0,
        dialogVisible: false,
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          departmentName: '',
          departmentName1: '',
          departmentCode: '',
          positionName: '',
          roleName: '',
          pageSize: 50,
          name: undefined,
          proPersonLiable: undefined,
          proDepartment: undefined,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        departmentList: [
        ],

        usersList: [
        ],
        listParent: [
        ],
        customerlist: [
        ],

        dialogTitle: '',

        activeName: 'myProject',

        rulesList: [
          {label: '管理员', value: '管理员'},
          {label: '言川一级用户', value: '言川一级用户'},
          {label: '言川二级用户', value: '言川二级用户'},
          {label: '言川三级用户', value: '言川三级用户'},

        ],

        rules: {
          proCode: [{ required: true, message: '项目编码必填', trigger: 'blur' }],
          proName: [{ required: true, message: '项目名称必填', trigger: 'blur' }],
          proPersonInitiator: [{ required: true, message: '项目发起人必选', trigger: 'blur' }],
          proPersonLiable: [{ required: true, message: '项目责任人必选', trigger: 'blur' }],
          proDepartment: [{ required: true, message: '项目所属部门必选', trigger: 'blur' }],
          proStartTime: [{ required: true, message: '项目起始时间必选', trigger: 'blur' }],
          proEndTime: [{ required: true, message: '项目终止时间必选', trigger: 'blur' }],
        }
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {
      this.getList()
      this.getRoleList()
      this.getDepartmentList()
      this.getDepartmentList1()

      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })

    },
    mounted() {
      // 测试用
      // var that = this
      // setTimeout(function() {
      //   that.dialogFormVisible = true
      // }, 5000)

      // alert(this.$store.getters.selectedTenantId);
    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: {
      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        //获取后端数据
        const { content } = await myProject.getProjectList(this.listQuery)
        this.list = content.list
        this.total = content.totalCounts
      },


      async getCustomerList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        //获取后端数据
        const { content } = await customerManage.getCustomerManageInfoList(this.listQuery)
        this.customerlist = content.list
      },


      async getListParent() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        //获取后端数据
        const { content } = await myProject.getProjectListParent(this.listQuery)
        this.listParent = content;


      },



      async getDepartmentList() { // 获取列表数据

        const { content } = await department.getDepartmentList(this.listQuery)
        this.departmentList = content.list;

      },
      async getDepartmentList1() { // 获取列表数据

        const { content } = await department.getDepartmentList(this.listQuery)
        this.departmentList1 = content.list;

      },




      async getRoleList() { // 获取列表数据

        const { content } = await department.getRoleList(this.listQuery)
        this.rulesList = content.list;

      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },

      handleCreate() {
        this.dialogVisible = true
        this.dialogTitle = '项目新增'
        this.listQuery = {};
        this.getListParent();
        this.getCustomerList();
      },
      handleUpdate(row) {
        this.dialogVisible = true
        this.dialogTitle = '项目编辑'
        this.listQuery = row;
        this.getCustomerList();

      },

      handleDelete(row) {
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          myProject.deleteProjectInfo(row.id).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })

      },

      reset() {
        this.listQuery.proName = ''
        this.listQuery.proPersonLiable = ''
        this.listQuery.proDepartment = ''
        this.getList()
      },
      cancel() {
        this.listQuery.proName = ''
        this.listQuery.proPersonLiable = ''
        this.listQuery.proDepartment = ''
        this.dialogVisible = false;
        this.getList()
      },
      onSubmit(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.listQuery.tenantId = this.$store.getters.selectedTenantId
            if(this.dialogTitle=='项目新增'){
              myProject.createProject(this.listQuery).then((res) => {
                console.log(res);
                if(res.status==200){
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.listQuery.proName = ''
                  this.listQuery.proPersonLiable = ''
                  this.listQuery.proDepartment = ''
                  this.dialogVisible = false
                  this.getList();

                }
              })
            }else if(this.dialogTitle=='项目编辑'){
              myProject.updateProject(this.listQuery).then((res) => {
                console.log(res);
                if(res.status==200){
                  this.$notify({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.listQuery.proName = ''
                  this.listQuery.proPersonLiable = ''
                  this.listQuery.proDepartment = ''
                  this.dialogVisible = false
                  this.getList();

                }
              })
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });

      }
,
      async getUsersList() { // 获取列表数据
        this.usersList = []

        const { content } = await user.getUserList(this.listQuery)
        this.usersList = content.list

      },

      handleClick(tab, event) {
        console.log(tab, event);
      },



    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
</style>
